#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:          catalogView.py
# Author:      KuKei
# Create Date: 2011-10-24
# Description: 目录管理视图
# Modify Date: 2011-10-24

from sd.cms.views.admin import AdminBaseView
from sd.cms.lib import Params, Result
from sd.cms.forms.paramForm import CatalogForm
from sd.cms.models.paramModel import Catalog
from sd.cms.models.appModel import Article
from django.db import transaction
from django.forms.util import ErrorDict

class CatalogView(AdminBaseView):
    def add(self, **args):
        catalogForm = CatalogForm()
        if self.request.POST:
            catalogForm = CatalogForm(self)
            if catalogForm.is_valid():
                formData = catalogForm.cleaned_data
                catalogModel = Catalog().initData(formData)
                if catalogModel.level == 20 and Catalog.objects.get(id=int(catalogModel.parent)).islast:
                    return self.render_json(Result(False,'终级目录不能添加子目录！','','',3))
                if Catalog.objects.valueCount(catalogModel.value)>0:
                    return self.render_json(Result(False,'目录值不能重复，请修改！','','',3))
                catalogModel.save()
                if int(catalogModel.parent) > 0 :
                    catalogParent = Catalog.objects.get(id=catalogModel.parent)
                    catalogParent.cnt = Catalog.objects.filter(parent=catalogParent.id).count()
                    catalogParent.save()
                self.mc.flushNS2(self.params.CATALOGS)
                self.result = Result(True,'操作成功！','','/admin/list!Catalog.html',2)
                self.viewData["etype"] = 'catalog'
                self.viewData["e"] = catalogModel
                self.result.html = self.render("/admin/snippet/element.html")._container[0]
            else:
                self.result = Result(False,catalogForm.GetErrors(),'','/admin/list!Catalog.html',3)
        return self.render_json()
    
    def edit(self, **args):
        catalogForm = CatalogForm()
        if self.request.POST:
            catalogForm = CatalogForm(self)
            if catalogForm.is_valid():
                formData = catalogForm.cleaned_data
                objId = int(self.request.POST['_id'])
                if objId > -1:
                    catalogModel = Catalog().initData(formData)
                    if Catalog.objects.valueCount(catalogModel.value, objId)>0:
                        return self.render_json(Result(False,'目录值不能重复，请修改！','','',3))
                    catalogModel.id = objId
                    catalogModel.cnt = Catalog.objects.filter(parent=objId).count()
                    catalogModel.save()
                    self.mc.flushNS2(self.params.CATALOGS)
                    self.result = Result(True,'操作成功！','','/admin/list!Catalog.html',2)
                    self.viewData["etype"] = 'catalog'
                    self.viewData["e"] = catalogModel
                    self.result.html = self.render("/admin/include/element.html")._container[0]
                else:
                    self.result = Result(False,catalogForm.GetErrors(),'','/admin/list!Catalog.html',3)
            else:
                self.result = Result(False,catalogForm.GetErrors(),'','/admin/list!Catalog.html',3)
        if self.request.POST.has_key('_retType') and self.request.POST['_retType'] == 'json':
            return self.render_json()
        else:
            self.viewData["result"] = self.result
            return self.render('/include/skip.html')
    
    def delete(self, **args):
        try:
            if self.request.POST:
                if Catalog.objects.filter(parent=int(args['id'])).count() > 0 :
                    self.result.flag = False
                    self.result.msg = "当前目录下存在子目录，不允许删除！"
                elif Article.objects.filter(catalog=int(args['id'])).count() > 0 :
                    self.result.flag = False
                    self.result.msg = "当前目录下存在内容，不允许删除！"
                else:
                    catalogModel = Catalog.objects.get(id=int(args['id']))
                    catalogModel.delete()
                    if catalogModel.parent > 0 :
                        catalogParent = Catalog.objects.get(id=catalogModel.parent)
                        catalogParent.cnt = Catalog.objects.filter(parent=catalogParent.id).count()
                        catalogParent.save()
                    self.mc.flushNS2(self.params.CATALOGS)
                    self.result.flag = True
                    self.result.msg = "删除成功！"
        except Exception,ex:
            self.result.flag = False
            self.result.msg = str(ex)
        if self.request.POST.has_key('_retType') and self.request.POST['_retType'] == 'json':
            return self.render_json()
        else:
            return self.redirect('/admin.list!Article.html')
    
    def listView(self, **args):
        catalogList, catalogModels = [], list(Catalog.objects.all().order_by('orderby'))
        for catalog in catalogModels:
            myCatalogForm = CatalogForm();
            catalogList.append(CatalogForm(self,modelData=catalog))
        catalognForm = CatalogForm()
        self.viewData['catalogList'] = catalogList
        self.viewData['catalogForm'] = catalognForm
        return self.render('/admin/listCatalog.html')
    
    def detailView(self, **args):
        catalog = Catalog.objects.get(id=int(args['id']))
        catalogForm = CatalogForm(self,modelData=catalog)
        #catalogForm.clearErrors()
        self.viewData["etype"] = 'detail'
        self.viewData["e"] = catalogForm
        return self.render('/admin/include/detail.html')
    
def action(request, **args):
    return apply(CatalogView(request).action, (), args)